import { observable, action, toJS } from 'mobx';
import { WeaLocaleProvider } from 'ecCom';
import { message, Modal } from 'antd';
import { getRandomString, compatibleHandle, openWindow, DocFileDownload } from '../../util';


const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;


/** ***   右键菜单相关   **** */

class RightMenu {
   constructor(parent) {
      this.parent = parent;
   }

   @observable sourceData = {};
   @observable current = 'myDisk'; // 当前使用的数据源
   @observable data = []; // 当前的右键菜单数据
   @observable ref = null;

   @action setRightMenuRef = (ref) => {
 this.ref = ref; 
}; // 设置ref


   // todo 调用API获取右键菜单数据
   @action getRightMenuData = () => {
      let datas = {
         status: false,
         myDisk: [],
         myDiskOpera: [],
         myShare: [],
         myShareOpera: [],
         colleaShare: [],
         colleaShareOpera: [],
      };

      // API.getRightMenu().then(res => {
      //    console.log("res",res);
         // res.status === true && (datas = res);
         // delete datas.status;

         // todo 接口稳定后将其删掉
         datas = {
            myDisk: [
               {
                  icon: 'icon-coms-upload',
                  content: '上传文件',
                  key: 'upload',
                  disabled: false,
               },
               {
                  icon: 'icon-coms-New-Flow',
                  content: '新建目录',
                  key: 'newFolder',
                  disabled: false,
               },
               {
                  icon: 'icon-coms-Supervise',
                  content: '查看',
                  key: 'look',
                  disabled: false,
                  allowSelect: true,
                  selectKey: ['iconView'],
                  itemGroup: [
                     {
                        icon: 'icon-coms-Modular-o',
                        content: '图标视图',
                        key: 'iconView',
                        disabled: false,
                     },
                     {
                        icon: 'icon-coms02-icon-Classified-view',
                        content: '列表视图',
                        key: 'listView',
                        disabled: false,
                     },
                  ],
               },
               {
                  icon: 'icon-coms-Refresh',
                  content: '刷新',
                  key: 'reFresh',
                  disabled: false,
               },
               {
                  icon: 'icon-coms-synchronization',
                  content: '排序方式',
                  key: 'sortMode',
                  disabled: false,
                  allowSelect: true,
                  selectKey: ['filename-sort'],
                  itemGroup: [
                     {
                        icon: 'icon-coms-content-o',
                        content: '文件名排序',
                        key: 'filename-sort',
                        disabled: false,
                     },
                     {
                        icon: 'icon-coms-overtime',
                        content: '修改时间排序',
                        key: 'uptime-sort',
                        disabled: false,
                     },
                  ],
               },
            ],
            myDiskOpera: [
               {
                  icon: 'icon-coms-Reopen',
                  content: '打开',
                  key: 'open',
                  disabled: false,
               },
               {
                  icon: 'icon-coms-download2',
                  content: '下载',
                  key: 'download',
                  disabled: false,
               },
               {
                  icon: 'icon-coms-Batch-sharing',
                  content: '分享',
                  key: 'share',
                  disabled: false,
               },
               {
                  icon: 'icon-coms-Release',
                  content: '发布到系统',
                  key: 'publish',
                  disabled: false,
               },
               {
                  icon: 'icon-coms-move',
                  content: '移动到',
                  key: 'move',
                  disabled: false,
               },
               {
                  icon: 'icon-coms-form-copy',
                  content: '复制',
                  key: 'Copy',
                  disabled: false,
               },
               {
                  icon: 'icon-coms-currency-Enclosure',
                  content: '重命名',
                  key: 'rename',
                  disabled: false,
               },
               {
                  icon: 'icon-coms-delete',
                  content: '删除',
                  key: 'delete',
                  disabled: false,
               },
            ],
            myShare: [
               {
                  icon: 'icon-coms-Supervise',
                  content: '查看',
                  key: 'look',
                  disabled: false,
                  allowSelect: true,
                  selectKey: ['iconView'],
                  itemGroup: [
                     {
                        icon: 'icon-coms-Modular-o',
                        content: '图标视图',
                        key: 'iconView',
                        disabled: false,
                     },
                     {
                        icon: 'icon-coms02-icon-Classified-view',
                        content: '列表视图',
                        key: 'listView',
                        disabled: false,
                     },
                  ],
               },
               {
                  icon: 'icon-coms-Refresh',
                  content: '刷新',
                  key: 'reFresh',
                  disabled: false,
               },
               {
                  icon: 'icon-coms-synchronization',
                  content: '排序方式',
                  key: 'sortMode',
                  disabled: false,
                  allowSelect: true,
                  selectKey: ['filename-sort'],
                  itemGroup: [
                     {
                        icon: 'icon-coms-content-o',
                        content: '文件名排序',
                        key: 'filename-sort',
                        disabled: false,
                     },
                     {
                        icon: 'icon-coms-overtime',
                        content: '修改时间排序',
                        key: 'uptime-sort',
                        disabled: false,
                     },
                  ],
               },
            ],
            myShareOpera: [
               {
                  icon: 'icon-coms-Reopen',
                  content: '打开',
                  key: 'open',
                  disabled: false,
               },
               {
                  icon: 'icon-coms-download2',
                  content: '下载',
                  key: 'download',
                  disabled: false,
               },
               {
                  icon: 'icon-coms-display',
                  content: '查看分享对象',
                  key: 'seeShareTarget',
                  disabled: false,
               },
               {
                  icon: 'icon-coms-go-back',
                  content: '取消分享',
                  key: 'cancelShare',
                  disabled: false,
               },
            ],
            colleaShare: [
               {
                  icon: 'icon-coms-Supervise',
                  content: '查看',
                  key: 'look',
                  disabled: false,
                  allowSelect: true,
                  selectKey: ['iconView'],
                  itemGroup: [
                     {
                        icon: 'icon-coms-Modular-o',
                        content: '图标视图',
                        key: 'iconView',
                        disabled: false,
                     },
                     {
                        icon: 'icon-coms02-icon-Classified-view',
                        content: '列表视图',
                        key: 'listView',
                        disabled: false,
                     },
                  ],
               },
               {
                  icon: 'icon-coms-Refresh',
                  content: '刷新',
                  key: 'reFresh',
                  disabled: false,
               },
               {
                  icon: 'icon-coms-synchronization',
                  content: '排序方式',
                  key: 'sortMode',
                  disabled: false,
                  allowSelect: true,
                  selectKey: ['filename-sort'],
                  itemGroup: [
                     {
                        icon: 'icon-coms-content-o',
                        content: '文件名排序',
                        key: 'filename-sort',
                        disabled: false,
                     },
                     {
                        icon: 'icon-coms-overtime',
                        content: '修改时间排序',
                        key: 'uptime-sort',
                        disabled: false,
                     },
                  ],
               },
            ],
            colleaShareOpera: [
               {
                  icon: 'icon-coms-Reopen',
                  content: '打开',
                  key: 'open',
                  disabled: false,
               },
               {
                  icon: 'icon-coms-download2',
                  content: '下载',
                  key: 'download',
                  disabled: false,
               },
               {
                  icon: 'icon-coms-Save-as',
                  content: '保存到云盘',
                  key: 'saveDisk',
                  disabled: false,
               },
            ],
         };

         // 添加点击事件、转换图标
         for (let a in datas) {
            datas.hasOwnProperty(a) && datas[a].forEach((i) => {
               i.icon = <i className={i.icon} />;
               // i.onClick = this.rightMenuOnClick;
               i.itemGroup && i.itemGroup.forEach((j) => {
                  j.icon = <i className={j.icon} />;
                  // j.onClick = this.rightMenuOnClick;
               });
            });
         }
         this.sourceData = datas;
         this.data = this.sourceData[this.current]; // 初始状态选用myDisk

      // });
   };

   // 更新右键菜单数据源
   @action updateRightMenuSource = (length) => {
      if (this.parent.topSelectedKey === 'netDisk') {
         length === 0 && (this.current = 'myDisk');
         length > 0 && (this.current = 'myDiskOpera');
      } else if (this.parent.topSelectedKey === 'share') {
         if (this.parent.shareTabSelectedKey === 'myShare') {
            length === 0 && (this.current = 'myShare');
            length > 0 && (this.current = 'myShareOpera');
         } else if (this.parent.shareTabSelectedKey === 'colleagueShare') {
            length === 0 && (this.current = 'colleaShare');
            length > 0 && (this.current = 'colleaShareOpera');
         }
      }
      this.data = this.sourceData[this.current];
   };

   // 更新当前右键菜单数据的 显隐和disabled状态
   @action updateRightMenuDisable = () => {
      let newData = [];
      this.data && this.data.forEach((i) => {
         // this.operationButtons.hasOwnProperty(i.key) && (i.disabled = this.operationButtons[i.key]);
         switch (i.key) {
            case 'Pastes': // 对“粘贴”的特殊处理
               i.disabled = this.parent.operationButtons[i.key];
               newData.push(i);
               break;
            default:
               // 当此项为true时，隐藏
               !(this.parent.operationButtons.hasOwnProperty(i.key) && this.parent.operationButtons[i.key]) && newData.push(i);
               break;
         }
      });
      this.data = newData;
   };

   // 右键菜单隐藏 "帮助" "显示页面地址" 加分隔线
   @action hideRightMenuUseless = () => {
      // 帮助 和 页面地址
      const helpDom = document.querySelector("ul[role='menu'].ant-menu-root .icon-coms-help");
      let url,
help;
      if (this.current.includes('Opera')) {
         url = false; help = 'none';
      } else {
         url = true; help = 'block';
      }
      this.ref && (this.ref.RightMenu.state.showUrlItem = url);
      helpDom && (helpDom.parentElement.parentElement.parentElement.style.display = help);


      // 处理分隔线
      // 粘贴的分割线
      let divideTag = document.querySelector("[netdisk='divide-paste']");
      if (this.data.length > 0 && this.data[0].key === 'Pastes') { // 如果在"粘贴"下方出现两个分割线，很有可能是：双击操作导致极短时间内发生两次onSelect事件，第一次执行DOM还未加上，第二次又进来执行
         if (!divideTag) // 解决办法是，函数节流。
         {
            let divideBefore;
            let newDivide = "<li class='ant-menu-item text-elli' netdisk='divide-paste'/>";
            let mounted = setInterval(() => {
               if (this.ref && this.ref.instanceIsMounted) // rightMenu组件是否已加载完成
               {
                  divideBefore = document.querySelector("ul[role='menu'].ant-menu-root .icon-coms-Paste");
                  divideBefore && divideBefore.parentNode.parentNode.parentNode.insertAdjacentHTML('afterEnd', newDivide);
                  clearInterval(mounted);
               }
            }, 1);
         }
      } else {
         divideTag && divideTag.parentElement.removeChild(divideTag);
      }
      // 发布到系统、复制下方的分割线
      let divideOperaTag = document.querySelectorAll('[netdisk]');
      if (this.current === 'myDiskOpera') {
         if (!divideOperaTag.length) {
            let release,
copy;
            let newDivide = "<li class='ant-menu-item text-elli' netdisk='divide'/>";
            let mounted = setInterval(() => {
               if (this.ref && this.ref.instanceIsMounted) // rightMenu组件是否已加载完成
               {
                  release = document.querySelector("ul[role='menu'].ant-menu-root .icon-coms-Release");
                  copy = document.querySelector("ul[role='menu'].ant-menu-root .icon-coms-form-copy");
                  release && release.parentNode.parentNode.parentNode.insertAdjacentHTML('afterEnd', newDivide);
                  copy && copy.parentNode.parentNode.parentNode.insertAdjacentHTML('afterEnd', newDivide);
                  clearInterval(mounted);
               }
            }, 1);
         }
      } else {
         for (let i = 0; i < divideOperaTag.length; i++) {
            divideOperaTag[i].parentElement.removeChild(divideOperaTag[i]);
         }
      }
   };

   // 右键菜单 “粘贴” 一项的变化
   @action changePasteItem = (keys) => {
      const length = keys.length;
      const myDisk = toJS(this.sourceData.myDisk);
      if (myDisk) {
         if (length > 0) {
            let pasteItem = {
               icon: <i className="icon-coms-Paste" />,
               content: '粘贴',
               key: 'Pastes',
               disabled: false,
            };
            myDisk[0] && myDisk[0].key !== 'Pastes' && this.pasteEffectRightMenu('add', pasteItem);
         } else {
            myDisk[0] && myDisk[0].key === 'Pastes' && this.pasteEffectRightMenu('delete'); // 去掉"粘贴"一项
         }
      }
   };
   @action pasteEffectRightMenu = (opera, newData) => {
      opera === 'add' && this.sourceData.myDisk.unshift(newData);
      opera === 'delete' && this.sourceData.myDisk.shift();
   };


   // 处理右键菜单的点击事件
   @action rightMenuOnClick = (key) => {
      // 当前被选择的keys / key
      const activeKeys = this.parent.fileSystem.tableStore.selectedRowKeys;
      const activeKey = activeKeys.length > 0 ? activeKeys[0] : null;
      const view = this.parent.viewSettings.type;

      console.log('rightMenu点击', key);
      switch (key) {
         case 'upload':
            this.parent.transportData.ref.throwMethod.uploadFile();
            break;
         case 'newFolder':
            this.rightHandle_newFolder();
            break;
         case 'look':
            break;
         case 'iconView':
            this.parent.changeView('icon');
            break;
         case 'listView':
            this.parent.changeView('list');
            break;
         case 'reFresh':
            this.parent.fileSystem.getTableDatas(); // 获取表格数据
            break;
         case 'sortMode':
            break;
         case 'filename-sort':
            this.rightHandle_sort('fileName');
            break;
         case 'uptime-sort':
            this.rightHandle_sort('upTime');
            break;
         case 'open':
            this.rightHandle_openFile(activeKey);
            break;
         case 'download':
            this.rightHandle_downloadFile(activeKey);
            break;
         case 'share':
            this.parent.setShareData({ visible: true });
            break;
         case 'publish':
            break;
         case 'move':
            this.parent.moveFilesData.ref && this.parent.moveFilesData.ref.openModal();
            break;
         case 'Copy':
            this.rightHandle_Copy('copy');
            break;
         case 'Pastes':
            this.rightHandle_paste();
            break;
         case 'rename':
            view === 'icon' && this.parent.viewSettings.IconViewRef.reNameFile(activeKey); // 调用ref方法 todo 修改title效果的数据
            view === 'list' && this.rightHandle_rename(); // 改变datas中的数据
            break;
         case 'delete':
            this.rightHandle_delete();
            break;
         case 'seeShareTarget':
            this.parent.lookTarget.visible = true;
            break;
         case 'cancelShare':
            confirm({
               title: '信息确认',
               content: '确定要取消分享吗？',
               onOk: this.rightHandle_cancelShare,
            });
            break;
         case 'saveDisk':
            break;
         default:
            console.error('right menu key非法', key);
            break;
      }
   };

   // 新建目录
   @action rightHandle_newFolder = () => {
      const { type, IconViewRef } = this.parent.viewSettings;
      let result;
      type === 'icon' && IconViewRef && (result = IconViewRef.newFolder()); // 通过ref调用方法
      type === 'list' && (result = this.listNewFolder());
      if (result.flag) {
         this.parent.fileSystem.clearSelection(); // 清空选中
         if (type === 'icon') {
            this.parent.fileSystem.setFileSystemData({ data: [result.metaData, ...this.parent.fileSystem.data] });
         } else if (type === 'list') {
            // todo checks合并的数据后期更改
            result.metaData = Object.assign(result.metaData, { randomFieldCk: 'true', randomFieldId: result.metaData.id, randomFieldOp: 'true' });
            this.parent.fileSystem.tableStore.datas = [result.metaData, ...this.parent.fileSystem.tableStore.datas];
            this.parent.fileSystem.setFileSystemData({ tableEdit: true });
         }
      } else {
         message.warn(result.msg);
      }
   };
   // 判断是否允许新建：列表视图
   @action listNewFolder = () => {
      let result = { flag: false, msg: '', metaData: {} };
      if (this.parent.fileSystem.tableEdit) {
         result.msg = '请完成当前编辑'; // todo 多语言
      } else {
         result.flag = true;
         result.metaData = {
            id: `folder_${getRandomString(6)}`,
            type: 'folder',
            textname: getLabel(513708, '新建目录'), // todo 多语言
            editing: true,
         };
         this.parent.fileSystem.setFileSystemData({ tableEdit: true });
         this.parent.fileSystem.clearSelection(); // 取消所有选中
      }
      return result;
   };

   // 复制操作 type为copy or move(ctrlX)
   @action rightHandle_Copy = (type) => {
      const copyData = {}; // 复制的 文件/目录 数据
      const selections = toJS(this.parent.fileSystem.tableStore.selectedRowKeys);
      if (selections.length === 0) {
 return; 
} // 如果没有选中，不执行任何操作
      const datas = this.parent.viewSettings.type === 'icon' ? toJS(this.parent.fileSystem.data) : toJS(this.parent.fileSystem.tableStore.datas);
      const msg = type === 'copy' ? '文件复制成功' : '文件剪切成功';

      // 如果是剪切,为选中的数据加上ctrlX样式,同时去掉其他数据的样式
      type === 'move' && this.parent.fileSystem.setFileSystemData({ data: datas.map((i) => {
 i.ctrlX = selections.includes(i.id); return i; 
}) });
      type === 'copy' && this.parent.fileSystem.setFileSystemData({ data: datas.map((i) => {
 i.ctrlX && (i.ctrlX = false); return i; 
}) });
      // 粘贴板数据
      datas.forEach((i) => {
 selections.includes(i.id) && (copyData[i.id] = { ...i }); 
});
      this.parent.pasteBoard.copyFiles(copyData); // 修改粘贴板
      this.parent.pasteBoard.pasteType = type;
      message.success(msg);
   };

   // 粘贴(右键菜单 + ctrlV的复制剪切)
   @action rightHandle_paste = () => {
      // 获得 ids from to 判断目标目录是否含有被复制文件，
      const pathRoute = toJS(this.parent.pathSearch.path);
      const pasteKeys = Object.keys(toJS(this.parent.pasteBoard.pasteData));
      if (pasteKeys.length === 0) return;
      const formFolder = this.parent.pasteBoard.pasteData[pasteKeys[0]].parentid;
      const aimFolder = pathRoute.length > 0 ? pathRoute[pathRoute.length - 1].id : 'home';
      // console.log("粘贴", pasteKeys, formFolder, aimFolder);

      // 错误情况处理
      if (formFolder === aimFolder) // 如果from to在相同目录下
      {
         message.warn('不能在同一目录下粘贴！');
         return;
      }
      if (pasteKeys.includes(formFolder) || pasteKeys.includes(aimFolder)) // 极端错误情况(将自己复制/移动到自己内部)
      {
         message.error('操作非法！');
         return;
      }

      const { safeKeys, repeatName } = this.checkRepeatNameToCopy(); // 检查有无重名
      const { fileIDs, folderIDs } = this.pickOutType(safeKeys, 'pastBord'); // 将safeKeys分成fileIDs和folderIDs
      console.log('ids', fileIDs, folderIDs);
      // todo 调用API 传参：type 及 被操作对象的 fileIDs, folderIDs，from，to


      // 接口返回true后 粘贴【1.清除ctrlX效果并加入data，2.选中 3.如果是移动(剪切),清空粘贴板】
      let newData = safeKeys.map((i) => {
 this.parent.pasteBoard.pasteData[i].ctrlX = false; return this.parent.pasteBoard.pasteData[i]; 
});
      const viewType = this.parent.viewSettings.type;
      viewType === 'icon' && (this.parent.fileSystem.data = [...toJS(this.parent.fileSystem.data), ...newData]);
      viewType === 'list' && (this.parent.fileSystem.tableStore.datas = [...toJS(this.parent.fileSystem.tableStore.datas), ...newData]);
      this.parent.fileSystem.tableStore.setSelectedRowKeys(safeKeys); // 选中
      if (this.parent.pasteBoard.pasteType === 'move') {
         // 清空粘贴板、清空pasteType
         this.parent.pasteBoard.copyFiles({});
         this.parent.pasteBoard.pasteType = '';
      }

      // 模态框提示重复的文件名 todo 将repeatName与接口返回值合并然后显示
      if (repeatName.length > 0) {
         let msg = '';
         let warnName = repeatName.concat(); // todo 合并即可
         warnName.forEach((item, index) => {
            index === 0 && (msg += `【${item}】`);
            index !== 0 && (msg += `、【${item}】`);
         });
         Modal.warning({
            title: '系统提示',
            content: (
               <div style={{ margin: '0 -25px' }}>目录下已存在同名文件：{msg}</div>
            ),
         });
      }
   };
   // 检查粘贴板和目标目录内的文件有无重名
   @action checkRepeatNameToCopy = () => {
      const pasteKeys = Object.keys(toJS(this.parent.pasteBoard.pasteData));
      const currentDatas = this.parent.viewSettings.type === 'icon' ? toJS(this.parent.fileSystem.data) : toJS(this.parent.fileSystem.tableStore.datas);
      const currentTextname = currentDatas.map(i => i.textname);
      let repeatName = []; // 重名的项
      const safeKeys = pasteKeys.filter((f) => {
         let textname = this.parent.pasteBoard.pasteData[f].textname;
         if (!currentTextname.includes(textname)) {
            return true; // 如果不重名
         }
            repeatName.push(textname); // 如果重名
      });
      return {
         safeKeys, // array keys
         repeatName, // array name
      };
   };
   // 将keys分拣成fileIDs、folderIDs
   @action pickOutType = (keys, source) => {
      let fileIDs = [],
folderIDs = [];
      if (source === 'pastBord') {
         const sourceData = toJS(this.parent.pasteBoard.pasteData);
         keys.forEach((i) => {
            sourceData[i].type === 'folder' && folderIDs.push(i);
            sourceData[i].type === 'file' && fileIDs.push(i);
         });
      } else if (source === 'data') {
         const sourceData = this.parent.viewSettings.type === 'icon' ? toJS(this.parent.fileSystem.data) : toJS(this.parent.fileSystem.tableStore.datas);
         sourceData.forEach((i) => {
            keys.includes(i.id) && i.type === 'folder' && folderIDs.push(i.id);
            keys.includes(i.id) && i.type === 'file' && fileIDs.push(i.id);
         });
      }
      return { fileIDs, folderIDs };
   };

   // 移动(浏览按钮 + 拖动)
   @action moveFiles = (to, keys) => {
      const { fileIDs, folderIDs } = this.pickOutType(keys, 'data'); // 将keys分成fileIDs和folderIDs
      const { type } = this.parent.viewSettings;
      const datas = type === 'icon' ? toJS(this.parent.fileSystem.data) : toJS(this.parent.fileSystem.tableStore.datas);
      console.log('调API', to, fileIDs, folderIDs);
      // todo 调用API  后端判断是否重名，需要将重名的提示出来

      let newData = datas.filter(i => !keys.includes(i.id)); // 更新展现数据
      type === 'icon' && this.parent.fileSystem.setFileSystemData({ data: newData });
      type === 'list' && (this.parent.fileSystem.tableStore.datas = newData);
      message.success('文件移动成功！');
   };


   // 文件排序 type:排序类型 fileName or upTime
   @action rightHandle_sort = (type) => {
      const sorted = {
         fileName: data => data.sort((a, b) => a.textname.localeCompare(b.textname, 'zh-CN')),
         upTime: data => data.sort((a, b) => a.uptime.localeCompare(b.uptime)),
      };
      let folderData = [],
fileData = [];
      let oldData = this.parent.viewSettings.type === 'icon' ? toJS(this.parent.fileSystem.data) : toJS(this.parent.fileSystem.tableStore.datas);
      oldData.forEach((i) => {
         i.type === 'folder' && folderData.push(i);
         i.type === 'file' && fileData.push(i);
      });
      let newData = sorted[type](folderData).concat(sorted[type](fileData));
      this.parent.viewSettings.type === 'icon' && this.parent.fileSystem.setFileSystemData({ data: newData });
      this.parent.viewSettings.type === 'list' && (this.parent.fileSystem.tableStore.datas = newData);
      this.data.find(f => f.key === 'sortMode').selectKey = [type === 'fileName' ? 'filename-sort' : 'uptime-sort'];
   };

   // 打开文件
   @action rightHandle_openFile = (id) => {
      openWindow(`/spa/document/index.jsp?id=${id}&isEdit=1&router=1#/main/document/edit`);
      // `/spa/document/index.jsp?id=${id}#/main/document/detail`
   };

   // 下载文件
   @action rightHandle_downloadFile = (id) => {
      id = '67049';
      let url = `/weaver/weaver.file.FileDownload?fileid=${id}&download=1`;
      DocFileDownload(id);
   };

   // 重命名：列表视图
   @action rightHandle_rename = () => {
      const selectedKeys = toJS(this.parent.fileSystem.tableStore.selectedRowKeys);
      if (selectedKeys.length === 1) {
         const key = selectedKeys[0],
newData = [...toJS(this.parent.fileSystem.tableStore.datas)];
         let value = '',
fullName = '',
flag = true;
         let data = newData.find(i => i.id === key);
         const canEdit = !this.parent.fileSystem.tableEdit; // 判断是否允许编辑(检查当前是否有正在编辑的项)
         if (canEdit) {
            data && (data.editing = true) && (value = fullName = data.textname);
            if (data.type === 'file') {
               value = value.split('.'); value.pop(); value = value.join('.');
            }
            [flag, fullName, value] = compatibleHandle(fullName, value, 'turn'); data.textname = fullName;
            this.parent.fileSystem.setFileSystemData({ tableEdit: true, tableInputValue: value });
            this.parent.fileSystem.tableStore.datas = newData;
         } else {
            message.warn('不能同时编辑多个');
         }
      } else {
         console.error('非法的重命名：选中了多个或没有选中');
      }
   };

   // 取消重命名：列表视图
   @action rightHandle_cancelRename = () => {
      this.parent.fileSystem.tableEdit = false;
      const newData = [...toJS(this.parent.fileSystem.tableStore.datas)];
      newData.forEach((i) => {
 i.editing = false; 
});
      this.parent.fileSystem.tableStore.datas = newData;
   };
   // 确认重命名：列表视图
   @action rightHandle_confirmRename = (key) => {
      // todo 调用API
      const newData = [...toJS(this.parent.fileSystem.tableStore.datas)];
      let textname = this.parent.fileSystem.tableInputValue;
      let data = newData.find(i => i.id === key);
      let flag = true,
name = this.parent.fileSystem.tableInputValue,
ext = data.textname.split('.').pop(),
fullName = `${name}.${ext}`;
      [flag, fullName, name] = compatibleHandle(fullName, name);
      // todo 重名验证
      if (flag && name) {
         data.textname = fullName; data.editing = false;
         this.parent.fileSystem.tableStore.datas = newData;
         this.parent.fileSystem.setFileSystemData({ tableEdit: false, tableInputValue: '' });
      }
      flag && !name && message.warn(getLabel(125692, '名称不能为空'));
   };

   // 删除
   @action rightHandle_delete = () => {
      const keys = this.parent.fileSystem.tableStore.selectedRowKeys;
      const oldData = this.parent.viewSettings.type === 'icon' ? toJS(this.parent.fileSystem.data) : toJS(this.parent.fileSystem.tableStore.datas);
      if (keys.length === 0) return;
      let newData = oldData.filter(f => !keys.includes(f.id));

      confirm({
         title: '信息确认',
         content: '确定删除选中项吗？',
         onOk: () => {
            // todo 调用API删除，返回true后处理前端
            this.parent.viewSettings.type === 'icon' && this.parent.fileSystem.setFileSystemData({ data: newData });
            this.parent.viewSettings.type === 'list' && (this.parent.fileSystem.tableStore.datas = newData);
            this.parent.fileSystem.clearSelection(); // 清空选中
         },
      });
   };

   // 取消分享
   @action rightHandle_cancelShare = () => {
      // todo 调用API
   };
}


export default RightMenu;
